<!--
 * @Author: Charsen
 * @Date: 2025-08-05 10:37
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:34:32
 * @Description: 
-->
<template>
  <Content :return-route="getReturnRoute">
    <SearchHeader
      ref="searchHeaderRef"
      :search-former="searchFormer"
      container-class="flex-y-center justify-between mb-10px"
      @on-search="handleSearch"
      @on-reset="handleSearch"
    >
      <template #right-buttons>
        <OptionReturn
          v-action="actions.index"
          :right="true"
          :return-route="getReturnRoute"
          :show-text="true"
        />
      </template>
    </SearchHeader>

    <TableWrapper
      ref="multipleTableRef"
      :left-span="leftSpan"
      :columns="columns"
      :list="list"
      :actions="actions"
      :loading="listLoading"
      :multi-select="multiSelect"
      :table-index="tableIndex"
      :page-former="pageFormer"
      row-class="body-container"
      @selection-change="handleSelectionChange"
      @on-force-del="handleForceDelete"
      @on-restore="onRestore"
    >
      <template #left-content>
        <slot name="left"></slot>
      </template>

      <template #header-options>
        <el-button
          v-if="multiSelect"
          v-action="actions.restore"
          :disabled="multipleSelection.length === 0"
          size="small"
          type="warning"
          @click="onRestoreBatch"
        >
          恢复
          <span class="i-custom-restore ml-6px wh-12px"></span>
        </el-button>
      </template>

      <template #pagination>
        <Pagination
          v-model:limit="pageFormer.page_limit"
          v-model:page="pageFormer.page"
          :total="pageFormer.total"
          @on-changed="fetchData"
        />
      </template>

      <!-- 传递所有插槽 -->
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData"></slot>
      </template>
    </TableWrapper>
  </Content>
</template>

<script setup lang="ts">
  import { api } from '#/api'
  import { useDestroy } from '#/hooks/useDestroy'
  import { useLister } from '#/hooks/useLister'
  import { useRestore } from '#/hooks/useRestore'
  import { ElTable } from 'element-plus'

  defineOptions({
    name: 'ScaffoldTrashed',
  })

  const props = withDefaults(
    defineProps<{
      actions: AclPermission
      entity: string
      leftSpan?: number
      multiSelect?: boolean
      queryParams?: object
      requestUrl?: RequestUrl
      returnByQuery?: boolean
      returnRoute?: string
      tableIndex?: boolean
    }>(),
    {
      returnRoute: '',
      actions: () => ({
        index: '',
        forceDel: '',
        restore: '',
      }),
      queryParams: () => ({}),
      multiSelect: true,
      tableIndex: true,
      returnByQuery: false,
      leftSpan: 0,
      requestUrl: () => ({
        trashed: '',
        params: {},
      }),
    }
  )

  const emits = defineEmits<{
    (e: 'on-fetched', res: object): void
    (e: 'on-deleted'): void
    (e: 'on-restored'): void
  }>()
  const multipleTableRef = ref<InstanceType<typeof ElTable>>()
  const multipleSelection = ref<any[]>([])
  const searchHeaderRef = ref()

  const {
    list,
    listLoading,
    columns,
    searchFormer,
    pageFormer,
    handleSearchChange,
    handleSearchChangeWith,
    fetchData,
    fetchDataWith,
  } = useLister({
    entity: props.entity,
    type: 'trashed',
    url: {
      trashed: api[props.entity]?.trashed,
      params: props.queryParams,
    },
  })

  const { handleForceDestroy, handleForceDestroyWith } = useDestroy({
    entity: props.entity,
    list,
  })

  const { handleRestore, handleRestoreWith, handleRestoreBatch, handleRestoreBatchWith } =
    useRestore({
      entity: props.entity,
      list,
    })

  const getReturnRoute = computed(() =>
    props.returnRoute === '' ? `${props.entity}Index` : props.returnRoute
  )

  const handleSelectionChange = (val: any[]) => (multipleSelection.value = val)
  const getSearchFormData = () => searchHeaderRef.value.getFormData()

  const handleForceDelete = (id: number | string): void => {
    props.requestUrl?.forceDestroy
      ? handleForceDestroyWith(
          { forceDestroy: props.requestUrl.forceDestroy, params: { ids: [id] } },
          () => emits('on-deleted')
        )
      : handleForceDestroy(id, () => emits('on-deleted'))
  }

  const onRestore = (id: number | string): void => {
    props.requestUrl?.restore
      ? handleRestoreWith({ restore: props.requestUrl.restore, params: { ids: [id] } }, () =>
          emits('on-restored')
        )
      : handleRestore(id, () => emits('on-restored'))
  }

  const onRestoreBatch = (): void => {
    props.requestUrl?.restore
      ? handleRestoreBatchWith(
          { restore: props.requestUrl.restore, params: { ids: getSelectIds() } },
          () => emits('on-restored')
        )
      : handleRestoreBatch(getSelectIds(), () => emits('on-restored'))
  }

  const getSelectIds = () => {
    return multipleSelection.value.map((item) => item.id)
  }

  const handleSearch = (data: object) => {
    props.requestUrl?.trashed
      ? handleSearchChangeWith(data, { trashed: props.requestUrl.trashed })
      : handleSearchChange(data)
  }

  const loadData = () => {
    const onFetched = (res: any) => {
      emits('on-fetched', res)
    }
    props.requestUrl?.trashed
      ? fetchDataWith(
          { trashed: props.requestUrl.trashed, params: props.requestUrl.params },
          onFetched
        )
      : fetchData(onFetched)
  }

  defineExpose({
    searchFormer,
    getSearchFormData,
    fetchData: loadData,
  })

  onMounted(() => {
    loadData()
  })
</script>
